package cn.xiaolang.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * 对象处理工具
 *
 * @author fuhw/Dean
 * @date 2019-12-26
 */
@Slf4j
public final class ObjectUtils {

    /**
     * 从磁盘读取
     *
     * @param filePath 磁盘路径
     * @param <T> 类型
     */
    public static <T> void readFromDisk(String filePath) {
        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath))) {
            log.info("serialize after:{}", (T) in.readObject());
        } catch (Exception e) {
            log.error("serialize exception:", e);
        }
    }

    /**
     * 刷到磁盘
     *
     * @param t 对象实例
     * @param filePath 磁盘路径
     * @param <T> 类型
     */
    public static <T> void flushToDisk(T t, String filePath) {
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filePath))) {
            log.info("flush to disk for serialize");
            out.writeObject(t);
            out.flush();
        } catch (IOException e) {
            log.error("flush to disk exception:", e);
        }
    }
}
